// matching-game.js - 单词配对游戏逻辑
const { playRightSound, playWrongSound, playClickSound } = require('../../../../utils/audioUtils.js');
const storageManager = require('../../../../manager/storageManager').getInstance();
const audioManager = require('../../../../manager/audioManager').getInstance();

Page({
  data: {
    score: 0,
    currentRound: 0,
    totalRounds: 6,
    progress: 0,
    leftWords: [],
    rightWords: [],
    selectedLeft: null,
    selectedRight: null,
    correctMatches: 0,
    wrongMatches: 0,
    gameOver: false,
    resultIcon: '',
    resultTitle: '',
    stars: 0,
    accuracy: 0,
    showToast: false,
    toastMessage: '',
    toastType: 'success'
  },

  onLoad: function() {
    const app = getApp();
    this.wordDataManager = app.globalData.wordDataManager;
    this.magicCoinManager = app.getMagicCoinManager();
    
    // 调用异步初始化方法
    this.initGame().catch(error => {
      console.error('游戏初始化失败:', error);
    });
  },

  // 初始化游戏
  initGame: async function() {
    // 显示加载提示
    wx.showLoading({
      title: '游戏初始化中...',
    });
    
    try {
      let words = this.getRandomWords(6);
      
      // 检查单词是否需要同步（丰富）
      const wordsToEnrich = words.filter(word => !this.wordDataManager._isWordEnriched(word));
      
      if (wordsToEnrich.length > 0) {
        // 同步（丰富）未丰富的单词
        console.log(`开始丰富 ${wordsToEnrich.length} 个单词数据`);
        await this.wordDataManager.enrichWords(wordsToEnrich.map(w => w.id));
        console.log('单词数据丰富完成');
        
        // 重新获取丰富后的单词数据
        words = words.map(word => {
          const enrichedWord = this.wordDataManager.getWordById(word.id);
          return enrichedWord || word;
        });
      }
      
      // 创建左侧英文单词列表
      const leftWords = words.map((word, index) => ({
        id: `left_${index}`,
        wordId: word.id,
        english: word.english,
        matched: false,
        pronunciation: word.pronunciation
      }));

      // 创建右侧中文释义列表（打乱顺序）
      const rightWords = this.shuffleArray(words.map((word, index) => ({
        id: `right_${index}`,
        wordId: word.id,
        chinese: word.chinese,
        matched: false
      })));

      this.setData({
        leftWords,
        rightWords,
        score: 0,
        currentRound: 0,
        correctMatches: 0,
        wrongMatches: 0,
        gameOver: false,
        selectedLeft: null,
        selectedRight: null
      });
    } catch (error) {
      console.error('游戏初始化失败:', error);
      wx.showToast({
        title: '游戏初始化失败，请重试',
        icon: 'none',
        duration: 2000
      });
    } finally {
      // 隐藏加载提示
      wx.hideLoading();
    }
  },

  // 获取随机单词
  getRandomWords: function(count) {
    const wordsDict = this.wordDataManager.getAllWords();
    // 将对象转换为数组，并过滤出有效的单词
    const allWords = Object.values(wordsDict).filter(word => word && word.english && word.chinese);
    if (allWords.length === 0) {
      console.error('没有可用的单词');
      return [];
    }
    const shuffled = this.shuffleArray(allWords);
    return shuffled.slice(0, Math.min(count, allWords.length));
  },

  // 打乱数组
  shuffleArray: function(array) {
    const newArray = [...array];
    for (let i = newArray.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [newArray[i], newArray[j]] = [newArray[j], newArray[i]];
    }
    return newArray;
  },

  // 选择左侧单词
  selectLeftWord: function(e) {
    // 播放点击音效
    playClickSound();
    
    const id = e.currentTarget.dataset.id;
    const word = this.data.leftWords.find(w => w.id === id);
    
    if (word.matched) return;

    this.setData({ selectedLeft: id });
    
    // 播放选中单词的音频
    if (word && word.english && word.wordId) {
      // 创建单词对象，包含必要的信息
      const wordObj = {
        id: word.wordId,
        english: word.english,
        pronunciation: word.pronunciation
      };
      
      // 使用audioManager播放单词发音
      audioManager.playPronunciation(wordObj, 1.0, 'american').catch(error => {
        console.error('播放单词发音失败:', error);
      });
    }
    
    // 如果已经选择了右侧单词，则检查匹配
    if (this.data.selectedRight) {
      this.checkMatch();
    }
  },

  // 选择右侧单词
  selectRightWord: function(e) {
    // 播放点击音效
    playClickSound();
    
    const id = e.currentTarget.dataset.id;
    const word = this.data.rightWords.find(w => w.id === id);
    
    if (word.matched) return;

    this.setData({ selectedRight: id });
    
    // 如果已经选择了左侧单词，则检查匹配
    if (this.data.selectedLeft) {
      this.checkMatch();
    }
  },

  // 检查匹配
  checkMatch: function() {
    const leftWord = this.data.leftWords.find(w => w.id === this.data.selectedLeft);
    const rightWord = this.data.rightWords.find(w => w.id === this.data.selectedRight);

    if (leftWord.wordId === rightWord.wordId) {
      // 匹配成功
      this.handleCorrectMatch(leftWord.id, rightWord.id);
    } else {
      // 匹配失败
      this.handleWrongMatch();
    }
  },

  // 处理正确匹配
  handleCorrectMatch: function(leftId, rightId) {
    const leftWords = this.data.leftWords.map(w => 
      w.id === leftId ? { ...w, matched: true } : w
    );
    const rightWords = this.data.rightWords.map(w => 
      w.id === rightId ? { ...w, matched: true } : w
    );

    const correctMatches = this.data.correctMatches + 1;
    const score = this.data.score + 100;
    const currentRound = correctMatches;
    const progress = (currentRound / this.data.totalRounds) * 100;

    this.setData({
      leftWords,
      rightWords,
      correctMatches,
      score,
      currentRound,
      progress,
      selectedLeft: null,
      selectedRight: null
    });

    this.showToast('太棒了！配对成功！', 'success');

    // 播放成功音效
    playRightSound();
    wx.vibrateShort({ type: 'light' });

    // 检查是否完成所有配对
    if (correctMatches === this.data.totalRounds) {
      setTimeout(() => {
        this.endGame();
      }, 500);
    }
  },

  // 处理错误匹配
  handleWrongMatch: function() {
    const wrongMatches = this.data.wrongMatches + 1;
    const score = Math.max(0, this.data.score - 20);

    this.setData({
      wrongMatches,
      score,
      selectedLeft: null,
      selectedRight: null
    });

    this.showToast('配对错误，再试一次！', 'error');
    
    // 播放错误音效
    playWrongSound();
    wx.vibrateShort({ type: 'heavy' });
  },

  // 显示提示信息
  showToast: function(message, type) {
    this.setData({
      showToast: true,
      toastMessage: message,
      toastType: type
    });

    setTimeout(() => {
      this.setData({ showToast: false });
    }, 1500);
  },

  // 结束游戏
  endGame: function() {
    const accuracy = Math.round((this.data.correctMatches / (this.data.correctMatches + this.data.wrongMatches)) * 100);
    let stars = 0;
    let resultIcon = '';
    let resultTitle = '';

    if (accuracy >= 90) {
      stars = 3;
      resultIcon = '🏆';
      resultTitle = '完美表现！';
    } else if (accuracy >= 70) {
      stars = 2;
      resultIcon = '🌟';
      resultTitle = '表现不错！';
    } else {
      stars = 1;
      resultIcon = '👍';
      resultTitle = '继续加油！';
    }

    // 奖励魔法币
    const coins = stars * 10;
    this.magicCoinManager.addMagicCoins(coins, `单词配对游戏 - ${stars}星`);

    // 保存游戏记录
    this.saveGameRecord(stars);

    this.setData({
      gameOver: true,
      accuracy,
      stars,
      resultIcon,
      resultTitle
    });
  },

  // 保存游戏记录
  saveGameRecord: function(stars) {
    try {
      // 保存游戏统计数据
    const gameStats = storageManager.getStorage(storageManager.STORAGE_KEYS.WORD_GAME_STATS) || {
        totalGamesPlayed: 0,
        totalStars: 0,
        highScore: 0,
        matching: { played: 0, bestScore: 0 },
        scramble: { played: 0, bestScore: 0 },
        memory: { played: 0, bestScore: 0 }
      };

      gameStats.totalGamesPlayed += 1;
      gameStats.totalStars += stars;
      gameStats.highScore = Math.max(gameStats.highScore, this.data.score);
      gameStats.matching.played += 1;
      gameStats.matching.bestScore = Math.max(gameStats.matching.bestScore, this.data.score);

      storageManager.setStorage(storageManager.STORAGE_KEYS.WORD_GAME_STATS, gameStats);

      // 保存最近游戏记录
    const recentGames = storageManager.getStorage(storageManager.STORAGE_KEYS.RECENT_WORD_GAMES) || [];
      recentGames.unshift({
        id: Date.now(),
        gameName: '单词配对',
        icon: '🎯',
        score: this.data.score,
        stars,
        timestamp: new Date().toISOString()
      });

      // 只保留最近10条记录
      storageManager.setStorage(storageManager.STORAGE_KEYS.RECENT_WORD_GAMES, recentGames.slice(0, 10));
    } catch (error) {
      console.error('保存游戏记录失败:', error);
    }
  },

  // 重新开始游戏
  restartGame: async function() {
    // 播放点击音效
    playClickSound();
    await this.initGame();
  },

  // 返回
  goBack: function() {
    // 播放点击音效
    playClickSound();
    wx.navigateBack();
  },
  
  // 转发给朋友
  onShareAppMessage: function() {
    return {
      title: `我在单词配对游戏中获得了${this.data.score}分！快来挑战吧！`,
      path: '/pages/challenge/word-games/matching-game/matching-game',
      // imageUrl: '/images/challenge.png'
    };
  },
  
  // 分享到朋友圈
  onShareTimeline: function() {
    return {
      title: `我在单词配对游戏中获得了${this.data.score}分！快来挑战吧！`,
      query: 'from=timeline',
      // imageUrl: '/images/challenge.png'
    };
  }
});
